package com.ruoyi.system.service.msg.handler;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.dto.AcceptanceChecklistSubmitDTO;
import com.ruoyi.system.dto.H5MsgConfirmDTO;
import com.ruoyi.system.entity.MsgPushTaskDO;
import com.ruoyi.system.entity.MsgPushTaskItemDO;
import com.ruoyi.system.enums.MsgTypeEnum;
import com.ruoyi.system.service.AcceptanceChecklistInstanceService;
import com.ruoyi.system.service.msg.H5MsgConfirmHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 阶段验收消息确认处理器
 * 处理阶段验收类型消息的确认逻辑，包括验收单填写记录提交
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Component
public class AcceptanceChecklistConfirmHandler implements H5MsgConfirmHandler {

    @Resource
    private AcceptanceChecklistInstanceService acceptanceChecklistInstanceService;

    @Override
    public boolean supports(Integer msgType) {
        return Objects.equals(msgType, MsgTypeEnum.ACCEPTANCE_CHECKLIST.getCode());
    }

    @Override
    public void handleConfirm(MsgPushTaskItemDO item, MsgPushTaskDO task, H5MsgConfirmDTO confirmDTO) {
        // 阶段验收需要提交验收单填写记录
        if (confirmDTO.getChecklistInstanceId() == null) {
            throw new ServiceException("阶段验收需要提交验收单实例ID");
        }
        
        if (confirmDTO.getChecklistRecords() == null || confirmDTO.getChecklistRecords().isEmpty()) {
            throw new ServiceException("阶段验收需要提交验收单填写记录");
        }
        
        // 构建验收单提交DTO
        AcceptanceChecklistSubmitDTO submitDTO = new AcceptanceChecklistSubmitDTO();
        submitDTO.setInstanceId(confirmDTO.getChecklistInstanceId());
        submitDTO.setH5UserId(confirmDTO.getH5UserId());
        submitDTO.setRecords(confirmDTO.getChecklistRecords());
        
        // 调用验收单服务来提交验收单填写记录
        Boolean submitResult = acceptanceChecklistInstanceService.submitChecklist(submitDTO);
        
        if (submitResult == null || !submitResult) {
            throw new ServiceException("验收单提交失败");
        }
        
        // 记录日志
        System.out.println("阶段验收确认成功，验收单实例ID: " + confirmDTO.getChecklistInstanceId() + 
                          ", 用户ID: " + confirmDTO.getH5UserId() + 
                          ", 填写记录数量: " + confirmDTO.getChecklistRecords().size());
    }
}
